<template>
  <div class="iam-user-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd" icon="Plus">
            新增用户
          </el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="userStore.userList" style="width: 100%">
        <el-table-column prop="user_id" label="用户ID" width="80" />
        <el-table-column prop="user_code" label="用户编号" />
        <el-table-column prop="user_name" label="用户姓名" />
        <el-table-column prop="hr_employee_code" label="员工编号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.is_active" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="last_login" label="最后登录" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑用户' : '新增用户'" width="500px" draggable>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户编号" prop="user_code">
          <el-input v-model="form.user_code" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="user_name">
          <el-input v-model="form.user_name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="员工编号" prop="hr_employee_code">
          <el-input v-model="form.hr_employee_code" placeholder="请输入员工编号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" type="email" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEditing" prop="password_hash">
          <el-input v-model="form.password_hash" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="form.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="300px">
      <p>确定要删除该用户吗？</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated, onDeactivated, reactive, markRaw } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useIamUserStore } from '@/stores/iam/IamUserStore'
import type { User } from '@/stores/iam/IamUserStore'

const userStore = markRaw(useIamUserStore()) // 使用markRaw避免不必要的响应式转换
const loading = ref(false)
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const formRef = ref<FormInstance>()
const isEditing = ref(false)
const selectedUserId = ref<number | null>(null)

// 定义表单数据
const form = reactive<Partial<User>>({})

// 定义表单验证规则
const rules = {
  user_code: [
    { required: true, message: '请输入用户编号', trigger: 'blur' }
  ],
  user_name: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' }
  ],
  hr_employee_code: [
    { required: true, message: '请输入员工编号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password_hash: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 修改 abortController 的定义和使用方式
let abortController: AbortController | null = null
let isComponentMounted = false
let isLoadingAborted = false // 跟踪加载是否被取消

// 生命周期钩子
onMounted(() => {
  console.log('IamUserPage mounted')
  isComponentMounted = true
  // 强制重新加载数据，确保每次组件挂载时都能获取最新数据
  loadUserList()
})

// 添加 activated 生命周期钩子，确保路由切换回来时也能重新加载数据
onActivated(() => {
  console.log('IamUserPage activated')
  isComponentMounted = true
  loadUserList()
})

// 增强组件卸载逻辑
onUnmounted(() => {
  console.log('IamUserPage unmounted')
  // 1. 先标记组件已卸载
  isComponentMounted = false

  // 2. 如果正在加载数据，标记为已取消
  if (loading.value) {
    isLoadingAborted = true
  }

  // 3. 取消所有未完成的请求
  if (abortController) {
    abortController.abort()
    abortController = null
  }

  // 4. 清空所有响应式状态
  loading.value = false
  dialogVisible.value = false
  deleteDialogVisible.value = false

  console.log('Component cleanup completed')
})

// 添加 deactivated 生命周期钩子
onDeactivated(() => {
  console.log('IamUserPage deactivated')
  // 组件失活时也需要进行清理
  isLoadingAborted = true
  if (abortController) {
    abortController.abort()
    abortController = null
  }
})

// 修改 loadUserList 函数，添加更强健的取消逻辑和强制刷新
const loadUserList = async () => {
  // 重置取消标志
  isLoadingAborted = false

  // 创建新的abort controller
  if (abortController) {
    abortController.abort()
  }
  abortController = new AbortController()

  if (!isComponentMounted) {
    console.log('Component not mounted, skipping loadUserList')
    return
  }

  loading.value = true
  try {
    console.log('Starting to fetch user list')
    // 强制刷新数据，不依赖缓存
    await userStore.fetchUserList(abortController.signal)

    // 再次检查组件是否已挂载且加载未被取消
    if (!isComponentMounted || isLoadingAborted) {
      console.log('Component unmounted or loading aborted after fetch')
      return
    }

    console.log('User list fetched successfully')
    // 确保数据已加载
    if (userStore.userList.length === 0) {
      console.warn('User list is empty, using mock data')
      // 如果获取的数据为空，手动设置为模拟数据
      userStore.userList = [...userStore.mockUsers]
    }
  } catch (error) {
    // 错误处理逻辑
    if ((error as Error).name === 'AbortError') {
      console.log('Fetch user list aborted')
    } else if (isComponentMounted && !isLoadingAborted) {
      ElMessage.error('获取用户列表失败')
      console.error('Error fetching user list:', error)
      // 确保有模拟数据显示
      if (userStore.userList.length === 0) {
        userStore.userList = [...userStore.mockUsers]
      }
    }
  } finally {
    // 确保在设置loading前检查组件是否仍在挂载中且加载未被取消
    if (isComponentMounted && !isLoadingAborted) {
      loading.value = false
    }
  }
}

// 其他方法保持不变，但要确保在每个异步操作前检查isComponentMounted
const handleSubmit = async () => {
  if (!formRef.value || !isComponentMounted) return

  try {
    await formRef.value.validate()

    // 创建新的abort controller用于这个操作
    const operationAbortController = new AbortController()

    if (isEditing.value && selectedUserId.value !== null) {
      await userStore.updateUser(selectedUserId.value, form, operationAbortController.signal)
      if (isComponentMounted) {
        ElMessage.success('用户编辑成功')
        dialogVisible.value = false
      }
    } else {
      const newUser: Omit<User, 'user_id' | 'created_at' | 'updated_at' | 'is_deleted'> = {
        user_code: form.user_code || '',
        user_name: form.user_name || '',
        hr_employee_code: form.hr_employee_code || '',
        password_hash: form.password_hash || '',
        is_active: form.is_active !== undefined ? form.is_active : true,
        email: form.email
      }

      await userStore.addUser(newUser, operationAbortController.signal)
      if (isComponentMounted) {
        ElMessage.success('用户新增成功')
        dialogVisible.value = false
      }
    }
  } catch (error) {
    if (isComponentMounted && (error as Error).name !== 'AbortError') {
      ElMessage.error(isEditing.value ? '用户编辑失败' : '用户新增失败')
    }
  }
}

// 其他函数也类似修改，确保在组件卸载时不会更新UI
const handleStatusChange = async (user: User) => {
  if (!isComponentMounted) return

  const originalStatus = user.is_active
  const operationAbortController = new AbortController()

  try {
    await userStore.updateUser(user.user_id, { is_active: user.is_active }, operationAbortController.signal)
    if (isComponentMounted) {
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    // 即使组件卸载，也要恢复用户状态以保持数据一致性
    user.is_active = originalStatus
    if (isComponentMounted && (error as Error).name !== 'AbortError') {
      ElMessage.error('状态更新失败')
    }
  }
}

const confirmDelete = async () => {
  if (selectedUserId.value === null || !isComponentMounted) return

  const operationAbortController = new AbortController()

  try {
    await userStore.deleteUser(selectedUserId.value, operationAbortController.signal)
    if (isComponentMounted) {
      ElMessage.success('用户删除成功')
      deleteDialogVisible.value = false
    }
  } catch (error) {
    if (isComponentMounted && (error as Error).name !== 'AbortError') {
      ElMessage.error('用户删除失败')
      deleteDialogVisible.value = false
    }
  }
}

const handleAdd = () => {
  if (!isComponentMounted) return

  isEditing.value = false
  selectedUserId.value = null
  // 重置表单
  Object.assign(form, {
    user_code: '',
    user_name: '',
    hr_employee_code: '',
    email: '',
    password_hash: '',
    is_active: true
  })
  dialogVisible.value = true
}

const handleEdit = (user: User) => {
  if (!isComponentMounted) return

  isEditing.value = true
  selectedUserId.value = user.user_id
  // 填充表单数据
  Object.assign(form, {
    user_code: user.user_code,
    user_name: user.user_name,
    hr_employee_code: user.hr_employee_code,
    email: user.email || '',
    is_active: user.is_active
  })
  dialogVisible.value = true
}

const handleDelete = (user: User) => {
  if (!isComponentMounted) return

  selectedUserId.value = user.user_id
  deleteDialogVisible.value = true
}
</script>

<style scoped>
.iam-user-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
